package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.TradeSkuOrderBean;
import com.atguigu.gmall.realtime.commont.Constant;
import com.atguigu.gmall.realtime.function.DimMapFunctionHbase;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;

import static org.apache.flink.api.common.state.StateTtlConfig.StateVisibility.NeverReturnExpired;

/**
 * @Author lzc
 * @Date 2023/5/4 09:33
 */
public class Dws_09_DwsTradeSkuOrderWindow_Cache_HBase extends BaseApp {
    public static void main(String[] args) {
        new Dws_09_DwsTradeSkuOrderWindow_Cache_HBase().init(
            40009,
            2,
            "Dws_09_DwsTradeSkuOrderWindow_Cache",
            Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 解析到pojo 中
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStream = parseToPojo(stream);
        // 2. 按照订单详情 id 去重
        SingleOutputStreamOperator<TradeSkuOrderBean> distinctedBeanStream = distinctByOrderDetailId(beanStream);
        // 3. 开窗聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> streamWithoutDims = windowAndAgg(distinctedBeanStream);
        // 4. 补充维度
        SingleOutputStreamOperator<TradeSkuOrderBean> streamWitDims = joinDims(streamWithoutDims);
        streamWitDims.print();
    
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> joinDims(
        SingleOutputStreamOperator<TradeSkuOrderBean> stream) {
        
        SingleOutputStreamOperator<TradeSkuOrderBean> skuInfoStream = stream
            .map(new DimMapFunctionHbase<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_sku_info";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getSkuId();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setSkuName(dim.getString("sku_name"));
                    bean.setSpuId(dim.getString("spu_id"));
                    bean.setTrademarkId(dim.getString("tm_id"));
                    bean.setCategory3Id(dim.getString("category3_id"));
                }
            });
        
        SingleOutputStreamOperator<TradeSkuOrderBean> spuInfoStream = skuInfoStream
            .map(new DimMapFunctionHbase<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_spu_info";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getSpuId();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setSpuName(dim.getString("spu_name"));
                }
            });
        
        SingleOutputStreamOperator<TradeSkuOrderBean> tmStream = spuInfoStream
            .map(new DimMapFunctionHbase<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_trademark";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getTrademarkId();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setTrademarkName(dim.getString("tm_name"));
                }
            });
        
        SingleOutputStreamOperator<TradeSkuOrderBean> c3Stream = tmStream
            .map(new DimMapFunctionHbase<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category3";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory3Id();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setCategory3Name(dim.getString("name"));
                    bean.setCategory2Id(dim.getString("category2_id"));
                }
            });
        
        SingleOutputStreamOperator<TradeSkuOrderBean> c2Stream = c3Stream
            .map(new DimMapFunctionHbase<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category2";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory2Id();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setCategory2Name(dim.getString("name"));
                    bean.setCategory1Id(dim.getString("category1_id"));
                }
            });
        
        return c2Stream
            .map(new DimMapFunctionHbase<TradeSkuOrderBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category1";
                }
                
                @Override
                public String getId(TradeSkuOrderBean bean) {
                    return bean.getCategory1Id();
                }
                
                @Override
                public void addDim(TradeSkuOrderBean bean,
                                      JSONObject dim) {
                    bean.setCategory1Name(dim.getString("name"));
                }
            });
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> windowAndAgg(
        SingleOutputStreamOperator<TradeSkuOrderBean> stream) {
        return stream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeSkuOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            
            )
            .keyBy(TradeSkuOrderBean::getSkuId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeSkuOrderBean>() {
                    @Override
                    public TradeSkuOrderBean reduce(TradeSkuOrderBean value1,
                                                    TradeSkuOrderBean value2) throws Exception {
                        value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                        value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                        value1.setActivityAmount(value1.getActivityAmount().add(value2.getActivityAmount()));
                        value1.setCouponAmount(value1.getCouponAmount().add(value2.getCouponAmount()));
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
                    @Override
                    public void process(String skuId,
                                        Context ctx,
                                        Iterable<TradeSkuOrderBean> elements,
                                        Collector<TradeSkuOrderBean> out) throws Exception {
                        TradeSkuOrderBean bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                        bean.setTs(System.currentTimeMillis());  //
                        out.collect(bean);
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> distinctByOrderDetailId(
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStream) {
        return beanStream
            .keyBy(TradeSkuOrderBean::getOrderDetailId)
            .process(new KeyedProcessFunction<String, TradeSkuOrderBean, TradeSkuOrderBean>() {
                // 状态默认情况下, 用于存储于内存中.
                // 一般要根据业务,来给状态设置 ttl
                private ValueState<TradeSkuOrderBean> lastBeanState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    ValueStateDescriptor<TradeSkuOrderBean> stateDesc = new ValueStateDescriptor<>("lastBean", TradeSkuOrderBean.class);
                    StateTtlConfig conf = StateTtlConfig.newBuilder(org.apache.flink.api.common.time.Time.seconds(10))  // ttl时间
                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)  // ttl更新类型: OnReadAndWrite 当访问的时候,更新时间戳  OnCreateAndWrite 当创建或更新的时候才更新时间戳
                        .setStateVisibility(NeverReturnExpired)  // 状态的可见性: NeverReturnExpired 永远不反会过期的状态 ReturnExpiredIfNotCleanedUp 会返回还没有清理的过期状态
                        .useProcessingTime() // 状态是否过期,依据是处理时间(目前也只支持处理时间)
                        .build();
                    stateDesc.enableTimeToLive(conf);
                    lastBeanState = getRuntimeContext().getState(stateDesc);
                    
                }
                
                @Override
                public void processElement(TradeSkuOrderBean currentBean,
                                           Context ctx,
                                           Collector<TradeSkuOrderBean> out) throws Exception {
                    TradeSkuOrderBean lastBean = lastBeanState.value();
                    // 当第一条来了,直接输出
                    if (lastBean == null) {
                        out.collect(currentBean);
                    } else {
                        // 不是第一条, 应该用当前数据 - 上一条的数据
                        // 把减完后的数据存入到 lastBean, 然后输出
                        lastBean.setOriginalAmount(currentBean.getOriginalAmount().subtract(lastBean.getOriginalAmount()));
                        lastBean.setActivityAmount(currentBean.getActivityAmount().subtract(lastBean.getActivityAmount()));
                        lastBean.setCouponAmount(currentBean.getCouponAmount().subtract(lastBean.getCouponAmount()));
                        lastBean.setOrderAmount(currentBean.getOrderAmount().subtract(lastBean.getOrderAmount()));
                        out.collect(lastBean);
                    }
                    
                    // 当数据总是会放入到状态, 供下一条使用
                    lastBeanState.update(currentBean);
                }
            });
    }
    
    private SingleOutputStreamOperator<TradeSkuOrderBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(new MapFunction<String, TradeSkuOrderBean>() {
                @Override
                public TradeSkuOrderBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    return TradeSkuOrderBean.builder()
                        .skuId(obj.getString("sku_id"))
                        .originalAmount(obj.getBigDecimal("split_original_amount"))
                        .activityAmount(obj.getBigDecimal("split_activity_amount") == null ? new BigDecimal("0.0") : obj.getBigDecimal("split_activity_amount"))
                        .couponAmount(obj.getBigDecimal("split_coupon_amount") == null ? new BigDecimal("0.0") : obj.getBigDecimal("split_coupon_amount"))
                        .orderAmount(obj.getBigDecimal("split_total_amount"))
                        .ts(obj.getLong("ts") * 1000)
                        .orderDetailId(obj.getString("id"))
                        .build();
                }
            });
    }
}
/*
缓存的选择:
    1. 选择 flink 的状态(内部)
        好处:
            1. 状态数据结构丰富
            2. 状态在本地内存, 读写特别的快
        坏处:
            1. 占用 flink 的内存,影响到 flink. 可以通过加内存解决
            2. 当维度发生变化的时候,缓存中维度没有办法及时更新
            
    2. 外部缓存: redis  选择这个
        好处:
            1. 数据结构丰富
            2. 当维度发生变化的时候,缓存中维度可以及时更新
            
        坏处:
            1. 是外部内存, 每次都需要经过网络访问,速度不如本地内存
            
-----------------------\
redis 数据结构的选择:

string 选择 string
 key            value
 表名+id         json 格式的字符串
 
 dim_sku_info:1  {"ID": "", "SKU_NAME": "",...}
 
 好处:
    读写方便
    非常方便的给每条数据设置 ttl
 坏处:
    key 过多, 容易出现 key 冲突现象
    解决: 选择一个单独的库去缓存维度

list
 key            value
 表名            [{},{}]
 dim_sku_info   [{"ID": "", "SKU_NAME": "",...}, ....  ]
 
 好处:
    1. 写比较方便 lpush  rpush
    2. key 比较少: 一张表一个 key
 坏处:
    读不方便,比较慢: 查询一次, 需要读取这种表所有维度,然后遍历
    
 

set
  和 list 同样的问题

hash
  key               field       value
  表名                id         json 格式字符串
    dim_sku_info     1          {}
                     2          {}
                     
    好处:
        读写方便
        key 比较少,一张表一个 key
   坏处:
      不能单独给每条维度设置 ttl
zset
 

 */